extends Object
static func importToFile(projectDir:String,path:String):
	var config = ConfigFile.new()
	var err = config.load(path)
	if err == OK:
		var importer = config.get_value("remap","importer")
		if importer=="texture_atlas":
			var res_path = projectDir.plus_file(config.get_value("remap","path").replace("res://",""))
			var save_path = res_path.get_basename() + ".tres"
			binToTxt(res_path,save_path)
			var tempconfig = ConfigFile.new()
			var err2 = tempconfig.load(save_path)
			if err2 == OK:
				var rect2 = tempconfig.get_value("resource","region")
				var source_file = config.get_value("deps", "source_file")
				var atlas_file = projectDir.plus_file(config.get_value("params","atlas_file").replace("res://",""))
				if  source_file==null:
					print("import error4 ",path)
					return false
				var dest_files = config.get_value("deps", "dest_files")
				var source_file_full_path = projectDir.plus_file(source_file.replace("res://",""))
				
				var image = Image.new()
				image.load(atlas_file)
				var atlas = ImageTexture.new()
				atlas.create_from_image(image)
				var texture=AtlasTexture.new()
				texture.atlas = atlas
				texture.region = rect2
				texture.get_data().save_png(source_file_full_path)
				return true
			return false
		else:
			var source_file = config.get_value("deps", "source_file")
			if  source_file==null:
				print("import error3 ",path)
				return false
			var dest_files = config.get_value("deps", "dest_files")
			var source_file_full_path = projectDir.plus_file(source_file.replace("res://",""))
			if source_file_full_path.get_extension().to_lower()=="fbx":
				source_file_full_path = source_file_full_path.get_basename() + ".tscn"
			var file = File.new()
			for dest in dest_files:
				var dest_full_path = projectDir.plus_file(dest.replace("res://",""))
				if file.file_exists(dest_full_path) and not file.file_exists(source_file_full_path):
					res_covert(dest_full_path,source_file_full_path)
				else:
					print("import error2 ",path)
			return true
	else:
		print("import error:",path)
		return false
	
static func smplToWav(path:String,save_path:String):
	var resInterLoader:ResourceInteractiveLoader = ResourceLoader.load_interactive(path)
	var err = resInterLoader.poll()
	while err==OK:
		err = resInterLoader.poll()
	var res:AudioStreamSample = resInterLoader.get_resource()
	if not res:
		print("load error ",path)
		return false
	res.save_to_wav(save_path)
	if save_path.get_extension()!="wav":
		var dir = Directory.new()
		dir.rename(save_path+".wav",save_path)
	return true
	
static func ostrToOgg(path:String,save_path:String):
	var resInterLoader:ResourceInteractiveLoader = ResourceLoader.load_interactive(path)
	var err = resInterLoader.poll()
	while err==OK:
		err = resInterLoader.poll()
	var res:AudioStreamOGGVorbis = resInterLoader.get_resource()	
	if not res:
		print("load error ",path)
		return false
	var buf:PoolByteArray = res.get_data()
	var oggFile=File.new()
	oggFile.open(save_path,File.WRITE)
	oggFile.store_buffer(buf)
	oggFile.close()
	return true
	
static func mp3strToMp3(path:String,save_path:String):
	var resInterLoader:ResourceInteractiveLoader = ResourceLoader.load_interactive(path)
	var err = resInterLoader.poll()
	while err==OK:
		err = resInterLoader.poll()
	var res:AudioStreamMP3 = resInterLoader.get_resource()	
	if not res:
		print("load error ",path)
		return false
	var buf:PoolByteArray = res.get_data()
	var oggFile=File.new()
	oggFile.open(save_path,File.WRITE)
	oggFile.store_buffer(buf)
	oggFile.close()
	return true

static func hexStringToByteArray(key:String):
	var byteArray = []
	byteArray.resize(32)
	var char_a=ord('a')
	var char_9 = ord('9')
	var char_f = ord('f')
	var char_0 = ord('0')
	
	for i in range(0,32):
		var v = 0
		if i*2<len(key):
			var ct = ord(key.to_lower()[i*2])
			if ct>=char_0 && ct <= char_9:
				ct = ct - char_0
			elif ct>=char_a && ct<=char_f:
				ct = 10 + ct - char_a
			v |= ct<<4
		if i*2+1<len(key):
			var ct = ord(key.to_lower()[i*2+1])
			if ct>=char_0 && ct <= char_9:
				ct = ct - char_0
			elif ct>=char_a && ct<=char_f:
				ct = 10 + ct - char_a
			v |= ct
		byteArray[i]=v
	return byteArray
	
static func stexToSvg(path:String,save_path:String):
	var stex:StreamTexture = StreamTexture.new()
	var err = stex.load(path)
	if err!=OK:
		print("%s stexToSvg error: %d" % [path,err])
		return false
	var img:Image = stex.get_data()
	var data=img.get_data()
	var file:File = File.new()
	file.open(save_path, File.WRITE)
	print(data)
	file.store_string(data.get_string_from_ascii())
	file.close()
	return true

static func stexToPng(path:String,save_path:String):
	var stex:StreamTexture = StreamTexture.new()
	var err = stex.load(path)
	if err!=OK:
		print("%s load StreamTexture error: %d" % [path,err])
		return false
	var img:Image = stex.get_data()
	if img==null:
		print("invalid texture data :%s" % [path])
		return false
	if save_path.empty():
		save_path = path.get_basename() + ".png"
	err = img.save_png(save_path)
	if err!=OK:
		print("%s save error" % [path])
		return false
	return true
	
static func spatlasToAtlas(path:String,save_path:String = ""):
	var f:File = File.new()
	f.open(path,File.READ)
	var content = f.get_as_text()
	f.close()
	var jsonResult = JSON.parse(content).result
	var atlas_data = jsonResult["atlas_data"]
	var new_ext=".atlas"
	var save=""
	if save_path.empty():
		save = path.get_basename() + new_ext
	else:
		save = save_path.get_basename() + new_ext
	var file:File = File.new()
	file.open(save, File.WRITE)
	file.store_string(atlas_data)
	file.close()
	return true
	
static func spskelToskel(path:String,save_path:String = ""):
	var new_ext=".skel"
	var save=""
	if save_path.empty():
		save = path.get_basename() + new_ext
	else:
		save = save_path.get_basename() + new_ext
	Directory.new().copy(path,save)
	return true

static func binToTxt(path:String,save_path:String = ""):
	var ext = path.get_extension().to_lower()
	var new_ext=ext
	if ext == "scn":
		new_ext=".tscn"
	elif ext=="res":
		new_ext=".tres"
	elif ext=="fbx":
		new_ext=".tscn"
	var resInterLoader:ResourceInteractiveLoader = ResourceLoader.load_interactive(path)
	var err = resInterLoader.poll()
	if err!=OK:
		print("error:",err)
		return false
	while err==OK:
		err = resInterLoader.poll()
	var save=""
	if save_path.empty():
		save = path.get_basename() + new_ext
	else:
		save = save_path.get_basename() + new_ext
	print(save)
	err =ResourceSaver.save(save,resInterLoader.get_resource())
	if err!=OK:
		return false
	if save!=save_path:
		var dir = Directory.new()
		dir.rename(save,save_path)
	return true
	
static func resetProjectSetting(path):
	var file:File = File.new()
	file.open(path,File.READ)
	var magic=file.get_buffer(4).get_string_from_utf8()
	if magic!="ECFG":
		print("magic error: %s" % [path])
		file.close()
		return false
	var count = file.get_32()
	for __ in range(0,count):
		var key = file.get_buffer(file.get_32()).get_string_from_utf8()
		var base64 = Marshalls.raw_to_base64(file.get_buffer(file.get_32()))
		var varObj = Marshalls.base64_to_variant(base64,true)
		ProjectSettings.set_setting(key,varObj)

static func settingBinToTxt(path:String,save_path:String = ""):
	var file:File = File.new()
	file.open(path,File.READ)
	var magic=file.get_buffer(4).get_string_from_utf8()
	if magic!="ECFG":
		print("magic error: %s" % [path])
		file.close()
		return false
	var count = file.get_32()
	for __ in range(0,count):
		var key = file.get_buffer(file.get_32()).get_string_from_utf8()
		var base64 = Marshalls.raw_to_base64(file.get_buffer(file.get_32()))
		var varObj = Marshalls.base64_to_variant(base64,true)
		ProjectSettings.set_setting(key,varObj)
	file.close()
	if save_path.empty():
		save_path = path.get_basename() + ".godot"
	ProjectSettings.save_custom(save_path)
	return true
	
static func meshToTxt(path:String,save_path:String = ""):
	var file:File = File.new()
	file.open(path,File.READ)
	var magic=file.get_buffer(4).get_string_from_utf8()
	if magic!="ECFG":
		print("magic error: %s" % [path])
		file.close()
		return false
	var count = file.get_32()
	for __ in range(0,count):
		var key = file.get_buffer(file.get_32()).get_string_from_utf8()
		var base64 = Marshalls.raw_to_base64(file.get_buffer(file.get_32()))
		var varObj = Marshalls.base64_to_variant(base64,true)
		ProjectSettings.set_setting(key,varObj)
	file.close()
	if save_path.empty():
		save_path = path.get_basename() + ".godot"
	ProjectSettings.save_custom(save_path)
	return true
	
static func decompile_byte_code(ScriptClass,path:String,save_path:String = "",key:String = ""):
	var decompile = ScriptClass.new()
	if path.ends_with(".gde"):
		decompile.decompile_byte_code_encrypted(path,hexStringToByteArray(key))
	else:
		decompile.decompile_byte_code(path)
	var scriptText = decompile.get_script_text()
	if len(scriptText)<=0:
		return false
	var saveFile = File.new()
	saveFile.open(path.get_basename() + ".gd",File.WRITE)
	saveFile.store_string(scriptText)
	saveFile.close()
	return true

static func res_covert(path:String,save_path:String,script_class=null,key:String = ""):
	ResourceLoader.set_abort_on_missing_resources(false)
	var ext_name = path.get_extension()
	var result = false
	match ext_name:
		"binary":
			result = settingBinToTxt(path)
		"scn","res":
			result = binToTxt(path,save_path)
		"stex":
			if save_path.get_extension() == "svg":
				result = stexToSvg(path,save_path)
			else:
				result = stexToPng(path,save_path)
		"sample":
			result = smplToWav(path,save_path)
		"mesh":
			result = meshToTxt(path,save_path)
		"spskel":
			result = spskelToskel(path,save_path)
		"spatlas":
			result = spatlasToAtlas(path,save_path)
		"ostr","oggstr":
			result = ostrToOgg(path,save_path)
		"mp3str":
			result = mp3strToMp3(path,save_path)
		"gdc","gde":
			result = decompile_byte_code(script_class,path,save_path,key)
	return result
static func projectConvert(projectDir:String,path:String,script_class,key:String = ""):
	var ext_name = path.get_extension()
	var result = false
	match ext_name:
		"import":
			importToFile(projectDir,path)
		"remap":
			Directory.new().remove(path)
		_:
			result = res_covert(path,"",script_class,key)
	if ext_name=="gdc" or ext_name=="gde" or ext_name=="binary":
		if result:
			Directory.new().remove(path)

